package utils

import (
	"context"
	"errors"
	"github.com/gogf/gf/v2/database/gdb"
)

type daoInstance interface {
	Table() string
	Ctx(ctx context.Context) *gdb.Model
}

// IsUnique 字段是否唯一
func IsUnique(ctx context.Context, dao daoInstance, where interface{}, message string) error {
	if where == nil || len(message) == 0 {
		return errors.New("where condition cannot be empty")
	}
	if count, err := dao.Ctx(ctx).Where(where).Count(); err != nil {
		return err
	} else if count > 0 {
		return errors.New(message)
	}
	return nil
}
